﻿<template>
  <div class="material-withdrawal">
    <!-- 头部导航栏 -->
    <div class="header-bar">
      <div class="header-left">
        <div class="menu-icon">三</div>
        <div class="close-icon">×</div>
      </div>
      <div class="header-title">
        <span>领用申请</span>
        <span class="page-indicator">(46 of 121)</span>
      </div>
    </div>

    <!-- 主标题 -->
    <div class="main-title">
      <div class="title-bar"></div>
      <h1>领用申请</h1>
    </div>

    <!-- 表单容器 -->
    <div class="form-container">
      <form @submit.prevent="handleSubmit">
        <!-- 标题 -->
        <div class="form-item">
          <label class="form-label required">*标题:</label>
          <input 
            v-model="formData.title"
            type="text" 
            class="form-input"
            placeholder="请输入领衔"
            required
            :disabled="isViewMode"
          />
        </div>

        <!-- 用途描述 -->
        <div class="form-item">
          <label class="form-label required">*用途描述:</label>
          <textarea 
            v-model="formData.usageDescription"
            class="form-textarea"
            placeholder="请输入用途描述"
            required
            :disabled="isViewMode"
          ></textarea>
        </div>

        <!-- 领用人 -->
        <div class="form-item">
          <label class="form-label required">*领用人:</label>
          <input 
            v-model="formData.recipient"
            type="text" 
            class="form-input"
            placeholder="请输入领用人姓名"
            required
            :disabled="isViewMode"
          />
        </div>

        <!-- 领用日期 -->
        <div class="form-item">
          <label class="form-label required">*领用日期:</label>
          <input 
            v-model="formData.withdrawalDate"
            type="datetime-local" 
            class="form-input"
            required
            :disabled="isViewMode"
          />
        </div>

        <!-- 备注 -->
        <div class="form-item">
          <label class="form-label">备注:</label>
          <textarea 
            v-model="formData.note"
            class="form-textarea"
            placeholder="请输入备注"
            :disabled="isViewMode"
          ></textarea>
        </div>

        <!-- 选择领用项目 -->
        <div class="form-item">
          <label class="form-label required">*选择领用项目:</label>
          <div class="select-group">
            <select 
              v-model="selectedItem"
              class="form-select"
              @change="handleItemSelect"
              :disabled="loading || isViewMode"
            >
              <option value="">
                {{ loading ? '加载中...' : '请选择项目' }}
              </option>
              <option 
                v-for="item in availableItems" 
                :key="item.id" 
                :value="item.id"
              >
                {{ item.name }} (库存: {{ item.warehouseQuantity }})
              </option>
            </select>
            <button 
              type="button" 
              class="add-btn"
              @click="addItem"
              :disabled="!selectedItem || loading || isViewMode"
            >
              {{ loading ? '加载中...' : '添加' }}
            </button>
          </div>
        </div>

        <!-- 物品列表表格 -->
        <div class="items-table-container">
          <table class="items-table">
            <thead>
              <tr>
                <th>货物名称</th>
                <th>类型</th>
                <th>材质</th>
                <th>规格</th>
                <th>产地</th>
                <th>仓库数量</th>
                <th>领用数量</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in selectedItems" :key="index">
                <td>{{ item.name }}</td>
                <td>{{ item.type }}</td>
                <td>{{ item.material }}</td>
                <td>{{ item.specification }}</td>
                <td>{{ item.origin }}</td>
                <td>{{ item.warehouseQuantity }}</td>
                <td>
                  <input 
                    v-model.number="item.withdrawalQuantity"
                    type="number"
                    min="1"
                    :max="item.warehouseQuantity"
                    class="quantity-input"
                    :disabled="isViewMode"
                  />
                </td>
                <td>
                  <button 
                    type="button" 
                    class="delete-btn"
                    @click="removeItem(index)"
                    :disabled="isViewMode"
                  >
                    <span>删除</span>
                    <span class="delete-icon">×</span>
                  </button>
                </td>
              </tr>
              <tr v-if="selectedItems.length === 0">
                <td colspan="8" class="empty-row">
                  暂无选择的物品
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <button v-if="!isViewMode" type="submit" class="submit-btn">
            {{ isEditMode ? '更新' : '提交' }}
          </button>
          <button type="button" class="cancel-btn" @click="handleCancel">
            {{ isViewMode ? '返回' : '取消' }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { materialApi } from '@/api'

const router = useRouter()
const route = useRoute()

// 表单数据
const formData = reactive({
  title: '',
  usageDescription: '',
  recipient: '',
  withdrawalDate: '',
  note: '',
  createdTime: '' // 用于编辑模式保持原始创建时间
})

// 选中的项目ID
const selectedItem = ref('')

// 已选择的物品列表
const selectedItems = ref([])

// 可选择的物品列表 - 从API获取
const availableItems = ref([])

// 加载状态
const loading = ref(false)

// 检查模式
const isViewMode = computed(() => {
  return route.query.mode === 'view' && route.query.id
})

const isEditMode = computed(() => {
  return route.query.mode === 'edit' && route.query.id
})

// 获取物资统计数据
const fetchMaterialStatistics = async () => {
  try {
    loading.value = true
    const response = await materialApi.getMaterialStatistics({})

    if (response.code === 200) {
      // 将API返回的数据转换为组件需要的格式
      const data = response.data
      const items = Array.isArray(data) ? data : (data.items || [])
      
      availableItems.value = items.map(item => ({
        id: item.id,
        swNo: item.swNo,
        name: item.goodsName,
        type: item.typeName,
        material: item.materialName,
        specification: item.size,
        origin: item.origin,
        warehouseQuantity: item.endingBalanceQuantity,
        materialId: item.materialid,
        typeId: item.typeId
      }))
      console.log('物资统计数据加载成功:', availableItems.value)
    } else {
      throw new Error(response.message || '获取物资统计失败')
    }
  } catch (error) {
    console.error('获取物资统计失败:', error)
    alert('获取物资数据失败，请重试')
    // 使用模拟数据作为备用
    availableItems.value = [
      { id: 1, swNo: 'SW202510090001', name: '轮胎', type: '车辆用品', material: '橡胶', specification: '001', origin: '中国-上海市', warehouseQuantity: 10, materialId: 2, typeId: 1 }
    ]
  } finally {
    loading.value = false
  }
}

// 获取物资领用详情
const fetchMaterialWithdrawalDetail = async (id) => {
  try {
    loading.value = true
    const response = await materialApi.getMaterialWithdrawalDetail(id)

    if (response.code === 200) {
      const data = response.data
      console.log('物资领用详情数据:', data)
      
      // 填充表单数据
      formData.title = data.title || ''
      formData.usageDescription = data.usageDescription || ''
      formData.recipient = data.recipient || ''
      formData.note = data.note || ''
      formData.createdTime = data.createdTime || '' // 保存原始创建时间
      
      // 处理日期格式
      if (data.withdrawalDate) {
        const date = new Date(data.withdrawalDate)
        const localDateTime = new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, 16)
        formData.withdrawalDate = localDateTime
      }
      
      // 构建物品信息并添加到选择列表
      if (data.goodName && data.withdrawalQuantity) {
        selectedItems.value = [{
          id: data.id,
          swNo: data.processDetailCode,
          name: data.goodName,
          type: '车辆用品', // 从详情数据推断或使用默认值
          material: '橡胶', // 从详情数据推断或使用默认值
          specification: '001', // 从详情数据推断或使用默认值
          origin: '中国-上海市', // 从详情数据推断或使用默认值
          warehouseQuantity: 10, // 从详情数据推断或使用默认值
          withdrawalQuantity: data.withdrawalQuantity,
          materialId: 2,
          typeId: 1
        }]
      }
      
      console.log('表单数据填充完成:', formData)
      console.log('选择物品填充完成:', selectedItems.value)
    } else {
      throw new Error(response.message || '获取物资领用详情失败')
    }
  } catch (error) {
    console.error('获取物资领用详情失败:', error)
    alert('获取详情数据失败，请重试')
  } finally {
    loading.value = false
  }
}

// 处理物品选择
const handleItemSelect = () => {
  // 选择变化时的处理逻辑
}

// 添加物品到列表
const addItem = () => {
  if (!selectedItem.value) return
  
  const item = availableItems.value.find(item => item.id == selectedItem.value)
  if (!item) return
  
  // 检查是否已经添加过该物品
  const existingItem = selectedItems.value.find(selected => selected.id === item.id)
  if (existingItem) {
    alert('该物品已经添加过了')
    return
  }
  
  // 添加到选择列表
  selectedItems.value.push({
    ...item,
    withdrawalQuantity: 1
  })
  
  // 清空选择
  selectedItem.value = ''
}

// 移除物品
const removeItem = (index) => {
  selectedItems.value.splice(index, 1)
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 验证必填字段
    if (!formData.title.trim()) {
      alert('请输入标题')
      return
    }
    
    if (!formData.usageDescription.trim()) {
      alert('请输入用途描述')
      return
    }
    
    if (!formData.recipient.trim()) {
      alert('请输入领用人')
      return
    }
    
    if (!formData.withdrawalDate) {
      alert('请选择领用日期')
      return
    }
    
    if (selectedItems.value.length === 0) {
      alert('请至少选择一个领用项目')
      return
    }
    
    // 验证领用数量
    for (const item of selectedItems.value) {
      if (!item.withdrawalQuantity || item.withdrawalQuantity <= 0) {
        alert(`${item.name} 的领用数量必须大于0`)
        return
      }
      if (item.withdrawalQuantity > item.warehouseQuantity) {
        alert(`${item.name} 的领用数量不能超过仓库数量`)
        return
      }
    }
    
    if (isEditMode.value) {
      // 编辑模式：更新现有记录
      await handleUpdate()
    } else {
      // 新增模式：创建新记录
      await handleCreate()
    }
    
  } catch (error) {
    console.error('提交失败:', error)
    if (error.response?.data?.message) {
      alert(`提交失败: ${error.response.data.message}`)
    } else {
      alert('提交失败，请重试')
    }
  }
}

// 新增记录
const handleCreate = async () => {
  // 为每个物品分别提交API请求
  const submitPromises = selectedItems.value.map(async (item) => {
    const requestData = {
      id: 0, // 新增时ID为0
      title: formData.title,
      usageDescription: formData.usageDescription,
      recipient: formData.recipient,
      withdrawalDate: new Date(formData.withdrawalDate).toISOString(),
      note: formData.note,
      createdTime: new Date().toISOString(),
      goodName: item.name,
      withdrawalQuantity: item.withdrawalQuantity,
      processDetailCode: item.swNo || `MW${Date.now()}_${item.id}`
    }
    
    console.log('新增物品数据:', requestData)
    
    const response = await materialApi.addMaterialWithdrawal(requestData)
    
    return response
  })
  
  // 等待所有请求完成
  const results = await Promise.all(submitPromises)
  
  // 检查所有请求是否成功
  const allSuccess = results.every(result => result.code === 200)
  
  if (allSuccess) {
    alert('领用申请提交成功！')
    // 清空表单
    resetForm()
    // 跳转或刷新页面
    router.back()
  } else {
    throw new Error('部分物品提交失败')
  }
}

// 更新记录
const handleUpdate = async () => {
  // 编辑模式：通常只更新第一个物品（因为API设计是单个物品更新）
  const item = selectedItems.value[0]
  if (!item) {
    throw new Error('没有找到要更新的物品')
  }
  
  const requestData = {
    id: parseInt(route.query.id), // 使用路由中的ID
    title: formData.title,
    usageDescription: formData.usageDescription,
    recipient: formData.recipient,
    withdrawalDate: new Date(formData.withdrawalDate).toISOString(),
    note: formData.note,
    createdTime: formData.createdTime || new Date().toISOString(), // 保持原始创建时间
    goodName: item.name,
    withdrawalQuantity: item.withdrawalQuantity,
    processDetailCode: item.swNo || `MW${Date.now()}_${item.id}`
  }
  
  console.log('更新物品数据:', requestData)
  
  const response = await materialApi.updateMaterialWithdrawal(requestData)
  
  if (response.code === 200) {
    alert('领用申请修改成功！')
    // 跳转回列表页面
    router.back()
  } else {
    throw new Error(response.message || '修改失败')
  }
}

// 重置表单
const resetForm = () => {
  formData.title = ''
  formData.usageDescription = ''
  formData.recipient = ''
  formData.withdrawalDate = ''
  formData.note = ''
  formData.createdTime = ''
  selectedItem.value = ''
  selectedItems.value = []
}

// 取消操作
const handleCancel = () => {
  if (confirm('确定要取消吗？未保存的数据将丢失。')) {
    router.back()
  }
}

onMounted(() => {
  console.log('领用申请页面已加载')
  console.log('当前模式:', route.query.mode, 'ID:', route.query.id)
  
  // 设置默认领用日期为当前时间（仅在新增模式下）
  if (!isViewMode.value && !isEditMode.value) {
    const now = new Date()
    const localDateTime = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString().slice(0, 16)
    formData.withdrawalDate = localDateTime
  }
  
  // 如果是查看或编辑模式，加载详情数据
  if (isViewMode.value || isEditMode.value) {
    fetchMaterialWithdrawalDetail(route.query.id)
    // 编辑模式下也需要加载物资统计数据，以便用户修改选择
    if (isEditMode.value) {
      fetchMaterialStatistics()
    }
  } else {
    // 新增模式，加载物资统计数据
    fetchMaterialStatistics()
  }
})
</script>

<style scoped>
.material-withdrawal {
  min-height: 100vh;
  background-color: #ffffff;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 头部导航栏 */
.header-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 20px;
  background-color: #4a4a4a;
  color: white;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.menu-icon, .close-icon {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 16px;
}

.close-icon {
  font-size: 18px;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-indicator {
  color: #cccccc;
  font-size: 14px;
}

/* 主标题 */
.main-title {
  display: flex;
  align-items: center;
  padding: 20px 30px;
  gap: 15px;
}

.title-bar {
  width: 4px;
  height: 30px;
  background-color: #4caf50;
}

.main-title h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

/* 表单容器 */
.form-container {
  padding: 0 30px 30px;
  max-width: 1000px;
}

/* 表单项 */
.form-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
  gap: 15px;
}

.form-label {
  min-width: 120px;
  padding-top: 8px;
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.form-label.required::after {
  content: '*';
  color: #f44336;
  margin-left: 4px;
}

.form-input, .form-textarea, .form-select {
  flex: 1;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  font-family: inherit;
  transition: border-color 0.3s;
}

.form-input:focus, .form-textarea:focus, .form-select:focus {
  outline: none;
  border-color: #4caf50;
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

/* 选择组 */
.select-group {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}

.form-select {
  flex: 1;
  position: relative;
}

.add-btn {
  padding: 10px 20px;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.add-btn:hover:not(:disabled) {
  background-color: #1976d2;
}

.add-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

/* 物品表格 */
.items-table-container {
  margin: 30px 0;
  overflow-x: auto;
}

.items-table {
  width: 100%;
  border-collapse: collapse;
  background-color: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.items-table th {
  background-color: #f5f5f5;
  padding: 12px 8px;
  text-align: left;
  font-size: 14px;
  font-weight: 600;
  color: #333;
  border-bottom: 1px solid #ddd;
}

.items-table td {
  padding: 12px 8px;
  border-bottom: 1px solid #eee;
  font-size: 14px;
  color: #555;
}

.items-table tr:hover {
  background-color: #f9f9f9;
}

.quantity-input {
  width: 60px;
  padding: 4px 6px;
  border: 1px solid #ddd;
  border-radius: 3px;
  text-align: center;
  font-size: 13px;
}

.delete-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  background: none;
  border: none;
  color: #2196f3;
  cursor: pointer;
  font-size: 13px;
  padding: 4px 8px;
  border-radius: 3px;
  transition: background-color 0.3s;
}

.delete-btn:hover {
  background-color: #f5f5f5;
}

.delete-icon {
  font-size: 16px;
  font-weight: bold;
}

.empty-row {
  text-align: center;
  color: #999;
  font-style: italic;
  padding: 30px;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 40px;
  padding-top: 30px;
  border-top: 1px solid #eee;
}

.submit-btn {
  padding: 12px 40px;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-btn:hover {
  background-color: #1976d2;
}

.cancel-btn {
  padding: 12px 40px;
  background-color: white;
  color: #2196f3;
  border: 1px solid #2196f3;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn:hover {
  background-color: #f5f5f5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-bar {
    padding: 10px 15px;
  }
  
  .main-title {
    padding: 15px 20px;
  }
  
  .form-container {
    padding: 0 20px 20px;
  }
  
  .form-item {
    flex-direction: column;
    gap: 8px;
  }
  
  .form-label {
    min-width: auto;
    padding-top: 0;
  }
  
  .select-group {
    flex-direction: column;
    align-items: stretch;
  }
  
  .items-table-container {
    font-size: 12px;
  }
  
  .items-table th,
  .items-table td {
    padding: 8px 4px;
  }
  
  .action-buttons {
    flex-direction: column;
    align-items: center;
  }
  
  .submit-btn,
  .cancel-btn {
    width: 100%;
    max-width: 200px;
  }
}
</style>
